import {
    Button,
    Form,
    Input,
    InputNumber,
    Modal,
    Select,
    Space,
    Table,
    TableProps,
    Tabs
} from "antd";
import {Group, Operation, OperationMethods, OperationParamsType} from "../types";
import {useEffect, useState} from "react";
import {add_operation, del_operation, list_groups, list_operations, start_task} from "../api";

function Settings() {
    const [data, setData] = useState<Operation[]>([])
    const [groups, setGroups] = useState<Group[]>([])
    const [currentGroup, setCurrentGroup] = useState<number>()
    const [modal, contextHolder] = Modal.useModal();
    const [isModalOpen, setIsModalOpen] = useState(false);

    function loadOperations(group_id: number) {
        list_operations(group_id)
            .then(res => {
                setData(res)
            })
    }

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        form
            .validateFields()
            .then((operation) => {
                add_operation({...operation, group_id: currentGroup!}).then(() => {
                    form.resetFields();
                    setIsModalOpen(false);
                    loadOperations(currentGroup!)
                }).catch((err) => {
                    console.log(err)
                })
            })
            .catch((errorInfo) => {
                console.log('Validation failed:', errorInfo);
            });
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    useEffect(() => {
        list_groups()
            .then(res => {
                setGroups(res)
                if (res.length && res.length > 0) {
                    setCurrentGroup(res[0].id);
                    loadOperations(res[0].id);
                }

            })

    }, []);

    function getData(params: OperationParamsType) {

        if ('time' in params) {
            return `键位:${params.key}\r\n时间:${params.time} ms`
        }

        function viwScreenPoint(screenX: number, screenY: number) {
            console.log('屏幕位置:', screenX, screenY)
        }

        return <Button onClick={() => viwScreenPoint(params.screenX, params.screenY)}>查看服务位置</Button>
    }

    const columns: TableProps<Operation>['columns'] = [
        {
            title: '步骤',
            dataIndex: 'step',
            key: 'step',
        },

        {
            title: '类型',
            key: 'operation_type',
            dataIndex: 'operation_type',
            render: (_, {operation_type}) => (
                <>
                    {
                        OperationMethods.getTypeDescription(operation_type)
                    }
                </>
            ),
        },
        {
            title: '参数',
            key: 'params',
            dataIndex: 'params',
            render: (_, {params}) => (
                <>
                    {
                        getData(params)
                    }
                </>
            ),
        }
        ,
        {
            title: '备注',
            dataIndex: 'mark',
            key: 'mark',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: Operation) => (
                <Space size="middle">
                    <Button onClick={() => deleteOperation(record.id)}>删除步骤</Button>
                </Space>
            ),
        },
    ];

    async function deleteOperation(id: number) {
        const confirmed = await modal.confirm({
            title: '确认删除',
            content: '确认删除此操作',
        });

        if (!confirmed) {
            return
        }
        del_operation(id)
            .then(res => {
                if (res) {
                    loadOperations(currentGroup!);
                }
            });
    }

    function changeGroup(key: string) {
        console.log(key)
    }


    const [form] = Form.useForm<Operation>();
    const operation_type = Form.useWatch('operation_type', form);

    async function startTask() {
        const confirmed = await modal.confirm({
            title: '是否循环执行',
            content: '循环执行会在后台一直执行,直到关闭app程序',
        });
        start_task(currentGroup!, confirmed)
            .then(() => {
                if (!confirmed) {
                    modal.success({
                        content: '操作成功!'
                    });
                }
            })

    }

    return (
        <>
            <div className={' wh-full flex-1 flex flex-col justify-center  pt-20px'}>
                <Tabs className={'pl-20px'} items={groups.map((item) => {
                    return {
                        label: item.name,
                        key: `${item.id}`,
                    };
                })} onChange={changeGroup}/>
                <Space className={'pl-20px'}>
                    <Button type={"primary"} onClick={showModal}>添加</Button>
                </Space>
                <Table className={"w-full px-20px pt-20px"} columns={columns} rowKey={"id"} dataSource={data}/>
                <Button className={"w-80px self-center"} type={"primary"} onClick={startTask}>启动</Button>
                <div>{contextHolder}</div>
                <Modal title="添加动作" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <Form
                        name="basic"
                        form={form}
                        labelCol={{span: 8}}
                        wrapperCol={{span: 16}}
                        style={{maxWidth: 600}}
                        initialValues={{remember: true}}
                        autoComplete="off"
                    >
                        <Form.Item<Operation>
                            label="操作类型"
                            name="operation_type"
                            rules={[{required: true, message: '请选择操作类型'}]}
                        >
                            <Select options={OperationMethods.getDict()}/>
                        </Form.Item>

                        <Form.Item<Operation>
                            label="step"
                            name="step"
                            rules={[{required: true, message: '请输入步骤'}]}
                        >
                            <InputNumber/>
                        </Form.Item>
                        {OperationMethods.isTime(operation_type) &&
                            <>
                                <Form.Item label={'时间'} name={['params', 'time']}>
                                    <InputNumber/>
                                </Form.Item>
                                <Form.Item label={'按键'} name={['params', 'key']}>
                                    <Input/>
                                </Form.Item>
                            </>
                        }
                        {(!OperationMethods.isTime(operation_type)) &&
                            <div>
                                <Form.Item label={'X坐标'} name={['params', 'screenX']}>
                                    <InputNumber/>
                                </Form.Item>
                                <Form.Item label={'Y坐标'} name={['params', 'screenY']}>
                                    <InputNumber/>
                                </Form.Item>
                            </div>

                        }
                        <Form.Item<Operation>
                            label="备注"
                            name="mark"
                            rules={[{required: true, message: '备注信息'}]}
                        >
                            <Input/>
                        </Form.Item>
                    </Form>

                </Modal>
            </div>
        </>
    )
}

export default Settings;